package br.com.documentos.model.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletRequest;

import net.tanesha.recaptcha.ReCaptcha;
import net.tanesha.recaptcha.ReCaptchaFactory;
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

public class CaptchaUtil {

	//
	public static final String PRIVATE_KEY = "6Lc7NcwSAAAAAK6ago_pF6NaS1xDLBEOrmqPxm8s";
	public static final String PUBLIC_KEY = "6Lc7NcwSAAAAAEMBVQCLrYItsql1Cveahu6HvvSZ";
	
	public static final String RECAPTCHA_HTML_ATRIBUTE = "RECAPTCHA_HTML";
	
	/**
	 * Valida se o CAPTCHA submetido esta correto
	 * @param request
	 * @return true se CAPTCHA valido
	 */
	public static boolean isValid( ServletRequest request )
	{
        String remoteAddr = request.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey(PUBLIC_KEY);

        String challenge = request.getParameter("recaptcha_challenge_field");
        String uresponse = request.getParameter("recaptcha_response_field");
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        return reCaptchaResponse.isValid();
	}
	
	public static void setCaptcha( ServletRequest request ){
		request.setAttribute(RECAPTCHA_HTML_ATRIBUTE, createHtml() );
	}
	
	public static String createHtml()
	{
		ReCaptcha c = ReCaptchaFactory.newReCaptcha(PRIVATE_KEY, PUBLIC_KEY, false);

		InputStream stream = CaptchaUtil.class.getClassLoader().getResourceAsStream("captcha.properties");
		
		String recaptchaHtml;
		
		try 
		{
			Properties properties = new Properties();
			properties.load(stream);
			
			recaptchaHtml = c.createRecaptchaHtml(null, properties);
		} 
		catch (IOException e) 
		{
			recaptchaHtml = c.createRecaptchaHtml(null, null);
		}

		return recaptchaHtml;
	}
	
}
